<?php
namespace App\Api\User;

use PhalApi\Api;
use App\Domain\User\User as UserDomain;
use App\Domain\User\UserSession as UserSessionDomain;
use PhalApi\Exception\BadRequestException;


/**
 * 新版用户插件接口
 */
class UserNew extends Api {
    public function getRules() {
        return array(
            'login' => array(
                'username' => array('name' => 'username', 'require' => true, 'min' => 1, 'max' => 50, 'desc' => '账号'),
                'password' => array('name' => 'password', 'require' => true, 'min' => 6, 'max' => 20, 'desc' => '密码'),
            ),
            'getList' => array(
                'page' => array('name' => 'page', 'type' => 'int', 'min' => 1, 'default' => 1, 'desc' => '页码'),
                'page_size' => array('name' => 'page_size', 'type' => 'int', 'default' => 10, 'desc' => '每页数量'),
                'deptId' => array('name' => 'deptId', 'type' => 'int', 'desc' => '部门Id'),
                'phone' => array('name' => 'phone', 'type' => 'int', 'desc' => '手机号'),
                'status' => array('name' => 'status', 'type' => 'int', 'desc' => '状态'),
                'roleId' => array('name' => 'roleId', 'type' => 'int', 'desc' => 'roleId'),
                'username' => array('name' => 'username', 'type' => 'string', 'desc' => '用户名')
            ),
            'fixUser' => array(), // 修改用户信息
            'deleteUser' => array(
                'user_id' => array('name' => 'user_id', 'type' => 'int', 'require' => true, 'desc' => '用户ID')
            ),
        );
    }

    
    /**
     * 登录接口
     * @desc 根据账号和密码进行登录操作
     * @return array {
     *   success: boolean,
     *   data: {
     *     avatar: string,
     *     username: string,
     *     nickname: string,
     *     roles: string[],
     *     permissions: string[],
     *     accessToken: string,
     *     refreshToken: string,
     *     expires: string
     *   }
     * }
     */
    public function login() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        $username = $this->username;
        $password = $this->password;

        $domain = new UserDomain();
        $user = $domain->getUserByUsername($username, 'id');
        if (!$user) {
            throw new BadRequestException($username . '账号不存在');
        }

        $user_id = intval($user['id']);
        $is_login = $domain->login($username, $password);
        
        if (!$is_login) {
            throw new BadRequestException('帐号或密码错误');
        }

        $session = new UserSessionDomain();
        $token = $session->generate($user_id);
        
        $profile = $domain->getUserByUsername($username, '*');
        $roles = json_decode($profile['roles'] ?? '[]', true);
        
        \PhalApi\DI()->response->addResult('success', true);

        return array(
            'is_login' => $is_login,
            'user_id' => $user_id,
            'token' => $token,
            'avatar' => $profile['avatar'] ?? "https://img.wenfree.cn/logo/logo-yunkong.png",
            'username' => $username,
            'nickname' => $profile['nickname'] ?? '',
            'roles' => is_array($roles) ? $roles : [],
            'permissions' => array("read:system", "write:system", "delete:system"),
            'accessToken' => $token,
            'refreshToken' => $token, // Using same token for simplicity
            'expires' => date('Y/m/d H:i:s', strtotime('+7 days'))
        );
    }
    
    /**
     * 获取用户列表
     * @desc 获取用户分页列表
     * @return array {
     *   items: array 用户列表数据
     *   total: int 总记录数
     *   page: int 当前页码
     *   page_size: int 每页数量
     * }
     */
    public function getList() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');
        
        $page = $this->page;
        $pageSize = $this->page_size;

        $where = array();
        if (!empty($this->deptId)) {
            $where['deptId'] = $this->deptId;
        }
        if (!empty($this->username)) {
            $where['username like ?'] = '%'.$this->username."%";
        }
        if (!empty($this->phone)) {
            $where['mobile like ?'] = '%'.$this->phone."%";
        }
        if (isset($this->status)) {
            $where['status'] = $this->status;
        }
        if (!empty($this->roleId)) {
            $where['roleIds like ?'] = '%'.$this->roleId."%";
        }

        // return [$where, empty($this->status), $this->status];

        $total = \PhalApi\DI()->notorm->phalapi_user->where($where)->count();
        $items = \PhalApi\DI()->notorm->phalapi_user
            ->where($where)
            ->select('id,avatar,username,password,nickname,mobile,email,sex,status,remark,create_time,deptId,dept_name, roleIds')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->fetchAll();

        foreach ($items as &$item) {
            $item['dept'] = array(
                'id' => $item['deptId'],
                'name' => $item['dept_name']
            );
            $item['nickname'] = $item['nickname']? $item['nickname'] : $item['username'];
            $item['phone'] = $item['mobile'] ? $item['mobile'] : $item['username'];
            $item['createTime'] = $item['create_time'] ? date('Y-m-d H:i:s', strtotime($item['create_time'])) : time()*1000;
        }
        
        \PhalApi\DI()->response->addResult('success', true);
        return array(
            'list' => $items,
            'total' => $total,
            'currentPage' => $page,
            'pageSize' => $pageSize
        );
    }
    
    /**
     * 修改用户信息
     * @desc 根据用户ID修改用户基本信息
     * @return array {
     *   success: boolean 是否修改成功,
     *   message: string 提示信息
     * }
     */
    public function fixUser() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        $input = json_decode(file_get_contents('php://input'), true);
        if (empty($input)) {
            throw new BadRequestException('更新数据不能为空');
        }

        $id = $input['id'];

        // return $input;
  

        $result = \PhalApi\DI()->notorm->phalapi_user
            ->where('id', $id )
            ->update($input);
        

        if ($result) {
            \PhalApi\DI()->response->addResult('success', true);
            return array(
                'success' => true,
                'message' => '用户信息修改成功'
            );
        } else {
            throw new BadRequestException('用户信息修改失败');
        }
    }
    
    /**
     * 删除用户
     * @desc 根据用户ID删除用户
     * @return array {
     *   success: boolean 是否删除成功,
     *   message: string 提示信息
     * }
     */
    public function deleteUser() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        $user_id = $this->user_id;

        // 先检查用户是否存在
        $user = \PhalApi\DI()->notorm->phalapi_user
            ->where('id', $user_id)
            ->fetchOne();
        
        if (!$user) {
            throw new BadRequestException('用户不存在');
        }

        $result = \PhalApi\DI()->notorm->phalapi_user
            ->where('id', $user_id)
            ->delete();

        if ($result) {
            \PhalApi\DI()->response->addResult('success', true);
            return array(
                'success' => true,
                'message' => '用户删除成功'
            );
        } else {
            throw new BadRequestException('用户删除失败');
        }
    }
}